import { Component, OnInit } from '@angular/core';
import { ListComponent } from './list.component';
import { ListBottonsConfigService } from '../services/list-buttons-config.service';
import { EntityListStateService } from './entity-list.state.service';
import { ABP, ListService } from '@abp/ng.core';
import { Observable } from 'rxjs';

@Component({
  selector: '',
  template: ``,
})
export abstract class EntityListComponent<T extends { id: string }>
  extends ListComponent
  implements OnInit
{
  showSearchPanel: boolean;

  get models(): T[] {
    return this.stateService.models;
  }

  get totalCount(): number {
    return this.stateService.totalCount;
  }

  get isAllSelected(): boolean {
    return this.stateService.isAllSelected;
  }

  get indeterminate(): boolean {
    return this.stateService.indeterminate;
  }

  get selectedCount(): number {
    return this.stateService.selectedCount;
  }

  constructor(
    public readonly list: ListService<ABP.PageQueryParams>,
    public buttonConfigService: ListBottonsConfigService,
    public stateService: EntityListStateService<T>
  ) {
    super(list);
    this.list.sortKey = 'Id';
    this.list.sortOrder = 'desc';
  }

  ngOnInit(): void {
    this.buttonConfigService.approveButtonGroup.visable = false;
    this.buttonConfigService.outputButtonGroup.visable = false;

    this.buttonConfigService.onNewClick.subscribe(() => this.new());
    this.buttonConfigService.onDeleteClick.subscribe(() => this.delete());
    this.buttonConfigService.onRefreshClick.subscribe(() => this.refresh());

    this.stateService.onSelectedCountChanged.subscribe(selectedCount => {
      this.buttonConfigService.deleteButton.enabled = selectedCount > 0;
    });

    this.hookToQuery();
    this.afterInit();
  }

  protected afterInit() {}

  public new() {
    this.stateService.new();
  }

  public view(model: T) {
    this.stateService.view(model.id);
  }

  isModelSelected(model: T): boolean {
    return this.stateService.isModelSelected(model);
  }

  targetModelSelect(model: T) {
    this.stateService.targetModelSelect(model);
  }

  targetAllSelect() {
    this.stateService.targetAllSelect();
  }

  clearSelect() {
    this.stateService.clearSelect();
  }

  public refresh() {
    this.list.get();
  }

  public delete() {
    if (this.selectedCount > 0) {
      this.stateService.delete().then(() => this.refresh());
    }
  }

  protected onQuery(query: ABP.PageQueryParams): Observable<any> {
    return this.stateService.onQuery(query);
  }
}
